﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Kangaroo.Shell.Utils
{
    class CheckButtonGroup:IEnumerable<ToolStripButton>
    {
        private readonly HashSet<ToolStripButton> _buttons = 
            new HashSet<ToolStripButton>();

        Dictionary<ToolStripButton, ToolStripMenuItem> _dictionary = new Dictionary<ToolStripButton, ToolStripMenuItem>();
        public void Add(ToolStripButton button, ToolStripMenuItem item)
        {
            _dictionary.Add(button, item);
            button.Click += button_Click;
        }

        public void Remove(ToolStripButton button)
        {
            button.Click -= button_Click;
            _dictionary.Remove(button);
        }

        void button_Click(object sender, EventArgs e)
        {
            var clickedButton = (ToolStripButton) sender;
            if(clickedButton.Checked)
            {
                return;
            }

            foreach (var dictionary in _dictionary)
            {
                dictionary.Key.Checked = false;
                dictionary.Value.Checked = false;
            }
            clickedButton.Checked = true;
            _dictionary.FirstOrDefault(d => d.Key == clickedButton).Value.Checked = true;
        }

        #region Implementation of IEnumerable

        /// <summary>
        /// Returns an enumerator that iterates through the collection.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>1</filterpriority>
        public IEnumerator<ToolStripButton> GetEnumerator()
        {
            return _buttons.GetEnumerator();
        }

        /// <summary>
        /// Returns an enumerator that iterates through a collection.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
        /// </returns>
        /// <filterpriority>2</filterpriority>
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #endregion
    }
}
